<?php

require_once("lib/exception/internal_error_exception.php");
require_once("lib/exception/instance_not_found_exception.php");

require_once("lib/model/action.php");
require_once("model/article/dao/article_dao_factory.php");
require_once("model/articlefacade/to/article_chunk_to.php");

class Find_most_recent_articles_action implements Action {
	
	private $start_index;
	private $count;
	
	public function __construct($start_index, $count) {
		$this->start_index = $start_index;
		$this->count = $count;
	}
	
	public function do_execute() {
		try {			
			$dao = Article_dao_factory::singleton()->get_dao();
			$article_list = $dao->find_most_recent($this->start_index, $this->count);
			
			$more = false;
			if (count($article_list) > ($this->count+1)) {
				$e = new Exception("Result list too big");
				throw new Internal_error_exception($e);
			}
			else {
				if(count($article_list) == ($this->count+1)) { 
					unset($article_list[$this->count]);
					$more = true;		
				}		
			}
			
			return new Article_chunk_to($article_list, $more);
	
		}
		catch (Instance_not_found_exception $e) {
			throw new Model_exception($e);
		}
		catch (Internal_error_exception $e) {
			throw $e;
		}
		catch (Exception $e) {
			throw new Exception("Internal error exception --> " . $e);
		}
	}
	
}

?>
